package com.qfjg.webcore.common;

import jakarta.servlet.http.HttpServletRequest;

import java.net.InetAddress;

public class UserIPUtils {

    private static final String UNKNOWN = "unknown";
    private static final String LOCALHOST = "127.0.0.1";
    private static final String SEPARATOR = ",";
    private static final String HEADER_X_FORWARDED_FOR = "x-forwarded-for";
    private static final String HEADER_PROXY_CLIENT_IP = "Proxy-Client-IP";
    private static final String HEADER_WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    public static String getIPAddress(HttpServletRequest request) {
        String ip;
        try {
            ip = request.getHeader(HEADER_X_FORWARDED_FOR);
            if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip))
                ip =  request.getHeader(HEADER_PROXY_CLIENT_IP);
            if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip))
                ip =  request.getHeader(HEADER_WL_PROXY_CLIENT_IP);
            if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
                if(LOCALHOST.equals(ip)) {
                    try {
                        InetAddress inet = InetAddress.getLocalHost();
                        ip = inet.getHostAddress();
                    } catch (Exception ignored) {}
                }
            }
            //多个代理
            if(ip != null && ip.length() > 15) {
                int sepIndex = ip.indexOf(SEPARATOR);
                if(sepIndex > 0) ip = ip.substring(0, sepIndex);
            }
        } catch (Exception e) { ip = ""; }
        return ip;
    }

}
